package com.brycen.bio.file;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

/**
 * 使用DataInputStream字节流分段接受文件后缀和文件内容，接受顺序和客户端输出顺序要保持一致
 */
public class ClientThread extends Thread {
    private Socket socket;

    public ClientThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        FileOutputStream fos = null;
        DataInputStream dis = null;
        try {
            InputStream inputStream = socket.getInputStream();
            dis = new DataInputStream(inputStream);
            //严格按照客户端发送的顺序读取
            String suffix = dis.readUTF();

            fos = new FileOutputStream("/Users/liuyu/Desktop/iodemo/test/"+ UUID.randomUUID()+suffix);
            byte[] buffer = new byte[1024];
            int len;
            //当客户端发送shutdownOutput的时候，这边read就会读到-1，然后结束，都在一直会阻塞在read这边
            while ((len=dis.read(buffer))>0){
                fos.write(buffer,0,len);
            }
            System.out.println("保存文件成功");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (socket!=null){
                    socket.close();
                }
                if (dis!=null){
                    dis.close();
                }
                if (fos!=null){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}
